/*
** exec_cmd.c for  in /home/gomes_m//my-project-a-moi/server
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Fri Jul 26 13:07:16 2013 mickael gomes
** Last update Sat Jul 27 15:06:15 2013 mickael gomes
*/

#include		<stdio.h>
#include		<unistd.h>
#include		<stdlib.h>
#include		<sys/types.h>
#include		<sys/wait.h>
#include		"struct.h"
#include		"prototypes.h"

void			do_cmd(t_list *list)
{
  int			i = 0;
  int			bool = 1;
  char			*path;

  while (list->cmd->paths[i] && bool)
    {
      path = my_strcat_plus(list->cmd->paths[i], list->cmd->cmd, '/');
      if ((bool = access(path, X_OK | F_OK)) != 0)
	i++;
    }
  if (i == tab_len(list->cmd->paths))
    my_putstr(2, "Command not found\n", 0);
  else
    {
      path = my_strcat_plus(list->cmd->paths[i], list->cmd->cmd, '/');
      if (execve(path, list->cmd->cmd_tab, list->cmd->env) == -1)
	my_putstr(2, "Exec error.\n", 0);
    }
}

void			get_fork(t_list *list)
{
  int			pipefd[2];
  pid_t			son_pid;
  int			status;

  pipe(pipefd);
  son_pid = fork();
  wait(&status);
  if (son_pid == 0)
    {
      xclose(pipefd[0]);
      dup2(pipefd[1], 1);
      do_cmd(list);
    }
  else
    send_response(pipefd, list);
}
